/*
 * @Author: 晟松
 * @Date: 2021-12-12 13:01:03
 * @LastEditors: 晟松
 * @LastEditTime: 2022-02-04 22:39:05
 * @FilePath: \mini-vue3d:\Code\node\koa2\volunteer-service\src\main\util\UploadUtils.js
 * @Description: 配合koa-body的保存文件，和七牛云的token生成操作
 */
import dayjs from "dayjs";
import qiniu from "qiniu";
// 添加七牛用户的公钥和私钥
const accessKey = process.env.ACCESS_KEY;
const secretKey = process.env.SECRET_KEY;
const bucket = process.env.bucket;

const path = require("path");
const fs = require("fs");
/**
 * @description: 配合koa-body将文件存储下来
 * @param {*}
 * @return {*}
 */
export const uploadFile = (file) => {
    // 使用七牛云存储传来的文件
    return serverUpload(file);

    // 使用本地存储
    // return localSave(file);
};

export const localSave = (file) => {
    // 使用本地存储
    let remotefilePath = null;
    if (file) {
        // console.log("file: ", file);
        // 创建可读流，同时在ctx.request.files里面选出属性名为file的文件的path创建流
        const reader = fs.createReadStream(file["path"]);
        // 创建一个文件保存在哪里的路径
        let time = new Date().getTime();
        let filePath = path.resolve(__dirname, "../../upload/" + `${time}-${file["name"]}`);
        // 这就是返回给前端进行图片访问的url，需要配合前面设置的静态资源目录路径

        let key = `${time}-${file["name"]}`;
        remotefilePath = `http://127.0.0.1:4000/${key}`;
        // 创建可写流，即保存文件
        const upStream = fs.createWriteStream(filePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);
        return { remotefilePath, key, filePath };
    }
    return remotefilePath;
};

/**
 * @description: 配合七牛云生成客户端需要的上传文件的token
 * @param {*} key 保存在七牛云中的文件名
 * @return {*}
 */
export const upToken = (key) => {
    let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    // 默认token有效期为一小时
    let options = {
        scope: bucket + ":" + key, //七牛资源目录
        callbackBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
        callbackBodyType: "application/json",
    };
    let putPolicy = new qiniu.rs.PutPolicy(options);
    let uploadToken = putPolicy.uploadToken(mac);
    console.log("uploadToken: ", uploadToken);
    return uploadToken;
};

/**
 * @description: 七牛云的服务器直传，使用数据流的方式
 * @param {*}
 * @return {*}
 */
export const serverUpload = async (file) => {
    var config = new qiniu.conf.Config();
    // 空间对应的机房，这里是华南区域
    config.zone = qiniu.zone.Zone_z2;
    // 是否使用https域名
    //config.useHttpsDomain = true;
    // 上传是否使用cdn加速
    config.useCdnDomain = true;

    let key = new Date().getTime() + "-" + file.name;
    let uploadToken = upToken(key);

    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
    var readableStream = fs.createReadStream(file["path"]); // 可读的流

    // 注意必须使用promise包裹一下，不然回调函数中的值无法获取到
    let resBody = new Promise((resolve, reject) => {
        formUploader.putStream(uploadToken, key, readableStream, putExtra, function (respErr, respBody, respInfo) {
            if (respErr) {
                reject(respErr);
                throw respErr;
            }
            if (respInfo.statusCode == 200) {
                console.log("respBody", respBody);
                resolve(respBody);
            } else {
                console.log(respInfo.statusCode);
                console.log(respBody);
            }
        });
    });
    // console.log('resno',await resBody);

    return await resBody;
};
